<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\ProductCate;
use think\facade\Cache;
use think\facade\View;
use think\response\Json;
use app\common\model\Product as ProductModel;
use app\common\model\HistorySearch;
use app\common\model\Footprint;
use app\common\model\User;
use app\common\model\Seckill;
use app\common\model\SeckillProduct;
use app\common\model\Evaluate;
use app\common\model\Collect;
use app\common\model\ProductSpecData;
use app\common\model\ProductSpecValue;
use app\common\model\SpecItem;
use app\common\model\Freight;
use app\common\model\Order;
use app\common\model\ProductFull;
use app\common\facade\WeChatMini;
use app\common\controller\Config;
use app\common\model\OrderProduct;
use app\common\model\Carousel;
use app\common\tool\Result;


class Product extends Base
{
    //获取搜索关键词记录
    public function getHistory()
    {
        $history = HistorySearch::where(['is_del' => 0, 'uid' => $this->user->id])->value('title');
        if (!empty($history)) {
            $list['history'] = json_decode($history, true);
        } else {
            $list['history'] = '';
        }
        $list['keyword'] = ProductModel::where(['is_del' => 0])->distinct(true)->orderRaw('rand()')->limit(6)->column('keyword');
        return Result::success('获取成功！', $list);
    }

    //清空搜索记录
    public function emptySearch()
    {
        HistorySearch::where(['uid' => $this->user->id])->update(['title' => '']);
        return Result::success('已清空');
    }

    //获取商品多规格
    public function getProductSpec()
    {
        $param = $this->request->param();
        $data = ProductSpecValue::where(['pid' => $param['pid'], 'sku_id' => $param['sku_id']])->find();
        $level = User::getPrice($this->token, $data->vip_price);
        $data->vip_price = $level['price'];
        $data->level_title = $level['title'];
        return Result::success('获取成功！', $data);
    }

    //获取商品分类
    public function getProductCate()
    {

        $param = $this->request->param();
        $list = ProductCate::where(['is_del' => 0, 'pid' => 0, 'status' => 1])->field('id,title,icon')->order('sort asc')->select();
        if (isset($param['pid']) && !empty($param['pid'])) {
            $pid = $param['pid'];
        } else {
            $pid = $list[0]['id'];
        }
        $cate = ProductCate::where(['is_del' => 0, 'pid' => $pid, 'status' => 1])->field('id,title,pid,icon')->order('sort asc')->select();
        foreach ($cate as $k => $v) {
            $v['icon'] = handleImg($v['icon'], 'https');
            $cate[$k] = $v;
        }
        $product = ProductModel::where(['is_del' => 0, 'status' => 1])->field('id,title,vip_price,price,icon,sales')->distinct(true)->orderRaw('rand()')->limit(6)->select();
        $data['list'] = $list;
        $data['cate'] = $cate;
        $data['product'] = $product;
        $data['cateimsge'] = Carousel::getList(['type' => 3, 'is_del' => 0], true, 'sort', [], 'id,images,link');;
        return Result::success('获取成功！', $data);
    }

    //商品详情
    public function details($id)
    {

        $system = Config::lists();
        //print('<pre>');print_r($ProductFull);die;
        $token = $this->request->header('token');
        $info = ProductModel::where(['status' => 1, 'is_del' => 0, 'id' => $id])
            ->field('id,title,describe,vip_price,price,kill_price,icon,stock,sales,ratio1,rule_by,rule_num,content_text,images')->find();
        if (empty($info)) return json(['code' => -1, 'msg' => '商品不存在或已下架']);
        $url = 'https://' . $_SERVER['SERVER_NAME'] . '/uploads/';
        $info->content_text = htmlspecialchars_decode(str_replace('/uploads/', $url, $info->content_text));
        $info->content_text = str_replace('\\', '', $info->content_text);
        $level = User::getPrice($this->token, $info->vip_price);
        $info->vip_price = $level['price'];
        $info->level_title = $level['title'];
        if (!empty($token)) {
            $user = User::where(['token' => $token])->find();
            if (!empty($user)) {
                Footprint::addFootprint($id, $user); //写入足迹
                //判断是否是分销商
                if ($user->is_place == 1) {
                    $status = 1;
                } else {
                    $status = 0;
                }
                //判断是否收藏
                $uid = $user['id'];
                $collect = Collect::where(['is_del' => 0, 'uid' => $user->id, 'product_id' => $id])->count();
                $data['is_collect'] = $collect > 0 ? 1 : 0;
            } else {
                $data['is_collect'] = 0;
                $uid = 0;
                $status = 0;
            }
        } else {
            $status = 0;
            $uid = 0;
            $data['is_collect'] = 0;
        }
        if ($status == 1) {
            $data['yjtitle'] = '可获得佣金￥' . round(($info->vip_price * $system['tp_1']), 2);
        } else {
            $data['yjtitle'] = '';
        }

        $commentlist = Evaluate::where(['product_id' => $id, 'is_del' => 0])->field('id,uid,content,create_time,pronum')->with('user')->order('create_time desc')->limit(3)->select();
        // foreach($commentlist as $k=>$v){
        //     $v['user']['nickname']='匿名用户';
        //     $commentlist[$k]=$v;
        // }
        $commentcount = Evaluate::where(['product_id' => $id, 'is_del' => 0])->count();
        $product = ProductModel::where(['status' => 1, 'is_del' => 0, 'pick' => 1])->field('id,title,describe,price,vip_price,icon,stock,sales')->limit(6)->select();
        foreach ($product as &$v) {
            $level = User::getPrice($this->token, $v->vip_price);
            $v->vip_price = $level['price'];
            $v->level_title = $level['title'];
        }
        $data['status'] = $status;
        $data['info'] = $info;
        if ($info->rule_by == 1) {
            $title = '订单满' . $info->rule_num . '元包邮';
        } else if ($info->rule_by == 2) {
            $title = '订单满' . $info->rule_num . '件包邮';
        } else if ($info->rule_by == 3) {
            $title = '单商品满' . $info->rule_num . '元包邮';
        } else if ($info->rule_by == 4) {
            $title = '单商品满' . $info->rule_num . '件包邮';
        }
        $data['yunfei'] = $title;


        $ProductFull = ProductFull::getFull($id, $info->price);

        if (empty($ProductFull['list'])) {
            $data['youhuiname'] = '';
            $data['youhuilist'] = '';
        } else {
            $data['youhuiname'] = implode(',', $ProductFull['list']['titlelist']);
            $data['youhuilist'] = $ProductFull['list'];
        }
        $data['commentlist'] = $commentlist;
        $data['commentcount'] = $commentcount;
        $data['product'] = $product;
        $data['freight'] = Freight::where(['is_del' => 0])->with('area')->order('sort asc')->select();
        $product_spec = ProductSpecData::where(['pid' => $id])->order('id asc')->select();
        foreach ($product_spec as $k => $v) {
            $clist = json_decode($v['child'], true);
            foreach ($clist as $kk => $vv) {
                $clist[$kk]['check'] = 0;
            }
            $v['list'] = $clist;
            $product_spec[$k] = $v;
        }
        $data['product_spec'] = $product_spec;
        $data['uid'] = $uid;
        return Result::success('获取成功！', $data);
    }

    //秒杀商品详情
    public function seckill_details($id, $seckill_id)
    {
        $system = Config::lists();
        $token = $this->request->header('token');
        $info = ProductModel::where(['status' => 1, 'is_del' => 0, 'id' => $id])
            ->field('id,title,describe,vip_price,price,kill_price,icon,stock,sales,ratio1,content_text,images')->find();
        if (empty($info)) return json(['code' => -1, 'msg' => '商品不存在或已下架']);
        $url = 'https://' . $_SERVER['SERVER_NAME'] . '/uploads/';
        $info->content_text = htmlspecialchars_decode(str_replace('/uploads/', $url, $info->content_text));
        $info->content_text = str_replace('\\', '', $info->content_text);
        if (!empty($token)) {
            $user = User::where(['token' => $token])->find();
            if (!empty($user)) {
                Footprint::addFootprint($id, $user); //写入足迹
                //判断是否是分销商
                if ($user->is_place == 1) {
                    $status = 1;
                } else {
                    $status = 0;
                }
                //判断是否收藏
                $uid = $user['id'];
                $collect = Collect::where(['is_del' => 0, 'uid' => $user->id, 'product_id' => $id])->count();
                $OrderCount = OrderProduct::where(['uid' => $user->id, 'pid' => $id, 'shoptype' => 'seckill'])->sum('num');
                $data['is_collect'] = $collect > 0 ? 1 : 0;
                $data['OrderCount'] = $OrderCount > 0 ? $OrderCount : 0;
            } else {
                $data['is_collect'] = 0;
                $data['OrderCount'] = 0;
                $uid = 0;
                $status = 0;
            }
        } else {
            $status = 0;
            $uid = 0;
            $data['is_collect'] = 0;
            $data['OrderCount'] = 0;
        }
        if ($status == 1) {
            $data['yjtitle'] = '可获得佣金￥' . round(($info->vip_price * $system['tp_1']), 2);
        } else {
            $data['yjtitle'] = '';
        }
        $Seckill = Seckill::where(['is_del' => 0, 'status' => 1, 'id' => $seckill_id])->field('id,title,end_time,start_time')->find();
        $commentlist = Evaluate::where(['product_id' => $id, 'is_del' => 0])->field('id,uid,content,create_time,pronum')->with('user')->order('create_time desc')->limit(3)->select();
        $commentcount = Evaluate::where(['product_id' => $id, 'is_del' => 0])->count();
        $product = ProductModel::where(['status' => 1, 'is_del' => 0, 'pick' => 1])->field('id,title,describe,price,vip_price,icon,stock,sales')->limit(6)->select();
        $data['status'] = $status;
        $data['info'] = $info;
        $data['commentlist'] = $commentlist;
        $data['commentcount'] = $commentcount;
        $data['product'] = $product;
        $data['freight'] = Freight::where(['is_del' => 0])->with('area')->order('sort asc')->select();
        $product_spec = ProductSpecData::where(['pid' => $id])->order('id asc')->select();
        foreach ($product_spec as $k => $v) {
            $clist = json_decode($v['child'], true);
            foreach ($clist as $kk => $vv) {
                $clist[$kk]['check'] = 0;
            }
            $v['list'] = $clist;
            $product_spec[$k] = $v;
        }
        if (!empty($Seckill)) {
            if ($Seckill['start_time'] < time() && $Seckill['end_time'] > time()) {
                $seckillproduct = SeckillProduct::where([['seckill_id', '=', $Seckill['id']], ['is_del', '=', 0], ['product_id', '=', $id]])->field('id,stock,seckill_id,num,sales,product_id')->find();
                $seckillproduct['bl'] = round(($seckillproduct['sales'] / ($seckillproduct['stock'] + $seckillproduct['sales']) * 100), 2) . '%';
            } else {
                $seckillproduct = [];
            }
            $count_down = $Seckill['end_time'] - time();
        } else {
            $seckillproduct = [];
            $count_down = 0;
        }
        $data['count_down'] = $count_down > 0 ? $count_down : 0;
        $data['seckill'] = $Seckill;
        $data['seckillproduct'] = $seckillproduct;
        $data['time'] = time2string($data['count_down']);
        $data['product_spec'] = $product_spec;
        $data['uid'] = $uid;
        return Result::success('获取成功！', $data);
    }

    //获取商品搜索
    public function getList()
    {
        $param = $this->request->param();
        //print_r($param);die;
        $map[] = ['is_del', '=', 0];
        $map[] = ['status', '=', 1];
        $key = 'create_time';
        $value = 'desc';
        $like = [];
        //关键词搜索
        if (isset($param['keyword']) && $param['keyword']) {
            $like['field'] = 'title';
            $like['keyword'] = $param['keyword'];
            if (!empty($param['keyword'])) {
                $token = $this->request->header('token');
                if ($token) {
                    $user = User::where(['token' => $token])->find();
                    if (!empty($user)) {
                        HistorySearch::setHistory($param['keyword'], $user);
                    }
                }
            }
        }
        //类型
        if (isset($param['cate']) && $param['cate']) {
            if ($param['cate'] == 1) {
                $key = 'create_time'; //综合排序
            } else if ($param['cate'] == 2) {
                $key = 'sales'; //销量排序
            } else if ($param['cate'] == 3) {
                $key = "vip_price"; //价格平排序
            } else if ($param['cate'] == 4) {
                $key = "create_time"; //上新排序
                $map[] = ['create_time', '>=', (time() - 86400 * 7)];
            } else {
                $key = 'create_time'; //默认排序
            }
        }
        //排序类型
        if (isset($param['types']) && $param['types']) {
            $value = $param['types'];
        }
        //分类id
        if (isset($param['pid']) && $param['pid']) {
            $catepid = ProductCate::where(['id' => $param['pid']])->find();
            if ($catepid['pid'] != 0) { //二级
                $pid = $catepid['pid'];
                $cate_id = 'cate_2';
            } else { //一级
                $pid = $param['pid'];
                $cate_id = 'cate_1';
            }
            $map[] = [$cate_id, '=', $param['pid']];
            $data['catelist'] = ProductCate::where(['is_del' => 0, 'pid' => $pid, 'status' => 1])->field('id,title,icon')->order('sort asc')->select();
        }
        $sort = ['key' => $key, 'value' => $value];
        //print_r($key);die;
        $list = ProductModel::getPageList($map, 'id,title,price,vip_price,icon,sales', $param['page'], 20, false, '', '', $sort, $like);
        foreach ($list['data'] as &$v) {
            $level = User::getPrice($this->token, $v->vip_price);
            $v->vip_price = $level['price'];
            $v->level_title = $level['title'];
        }
        $data['list'] = $list;
        $data['map'] = $map;
        return Result::success('获取成功！', $data);
    }

    //秒杀专区
    public function getSeckill()
    {

        $param = $this->request->param();
        $Seckill = Seckill::where(['is_del' => 0, 'status' => 1])->field('id,title,end_time,start_time')->find();

        if (!empty($Seckill)) {
            if ($Seckill['start_time'] < time() && $Seckill['end_time'] > time()) {
                if (!isset($param['status'])) {
                    $product = SeckillProduct::where([['seckill_id', '=', $Seckill['id']], ['is_del', '=', 0], ['stock', '>', 0]])->field('id,stock,seckill_id,num,sales,product_id')->limit(3)->with('product')->select();
                } else {
                    $product = SeckillProduct::where(['seckill_id' => $Seckill['id'], 'is_del' => 0])->field('id,stock,seckill_id,num,sales,product_id')->with('product')->select();
                }
            } else {
                $product = [];
            }

            $count_down = $Seckill['end_time'] - time();
        } else {
            $product = [];
            $count_down = 0;
        }
        if (!empty($product)) {
            foreach ($product as $k => $v) {
                $v['bl'] = round(($v['sales'] / ($v['stock'] + $v['sales']) * 100), 2) . '%';
                $product[$k] = $v;
            }
        }
        $data['count_down'] = $count_down > 0 ? $count_down : 0;
        $data['seckill'] = $Seckill;
        $data['product'] = $product;
        $data['time'] = time2string($data['count_down']);
        return Result::success('获取成功！', $data);
    }

    //订单详情
    public function order_detail()
    {
        $id = $this->request->param('id');
        $info = Order::where(['id' => $id])->with(['user', 'products'])->find();
        if (empty($info)) {
            return Result::fail('未查询到相关订单');
        }
        if ($info->getData('status') < 3) {
            $info->addressData = [
                'receiver'     => $info->address->nickname,
                'receiver_tel' => $info->address->tel,
                'province'     => $info->address->p->title,
                'city'         => $info->address->c->title,
                'district'     => $info->address->d->title,
                'details'      => $info->address->details
            ];
        } else {
            $info->addressData = [
                'receiver'     => $info->receiver,
                'receiver_tel' => $info->receiver_tel,
                'province'     => $info->p->title,
                'city'         => $info->c->title,
                'district'     => $info->d->title,
                'details'      => $info->address_details
            ];
            $info->expressData = [
                'express_id'    => $info->express_id,
                'express_code'  => $info->express_code,
                'express_title' => $info->express->title,
            ];
        }
        foreach ($info->products as $k => $v) {
            if (!empty($v->spec)) {
                $spce = explode('-', $v->spec);
                $Specname = SpecItem::whereIn('id', $spce)->column('name');
                $v->Specname = implode('-', $Specname);
            } else {
                $v->Specname = '默认';
            }
            $info->products->$k = $v;
        }

        $info->productsData = $info->products;
        $date = [
            'pay_time',
            'receipt_time',
            'comment_time',
            'finish_time',
            'refund_time',
            'cancel_time',
            'remind_time'
        ];
        foreach ($date as $v) {
            $info->$v = $info->$v ? date('Y-m-d H:i:s', intval($info->$v)) : '';
        }
        $unset = [
            'receiver',
            'receiver_tel',
            'province',
            'city',
            'district',
            'town',
            'address_details',
            'address',
            'uid',
            'address_id',
            'is_del',
            'order_type',
            'express',
            'express_id',
            'express_code',
            'update_time',
            'p',
            'c',
            'd',
            't',
            'products'
        ];
        foreach ($unset as $v) {
            unset($info->$v);
        }

        return Result::success('获取成功！', $info);
    }

    //商品提交
    public function submit()
    {
        $param = $this->request->post();
        $result = ProductModel::submit($param, $this->user);
        $result['code'] = $result['code'] >= 1 ? 1 : -1;
        return json($result);
    }

    //获取分享
    public function getShare()
    {
        $param = $this->request->get();
        $url = '/qrcode/product';
        if (isset($param['seckill_id']) && $param['seckill_id'] != 0) {
            $result = WeChatMini::getMiniScene($param['ids'] . ',' . $this->user->id . ',' . $param['seckill_id'], $this->user->id . '_' . $param['ids'] . '_' . $param['seckill_id'], '240', 'pages/product/seckill_detail', $url);
        } else {
            if ($this->user->is_place == 1) {
                $result = WeChatMini::getMiniScene($param['ids'] . ',' . $this->user->id, $this->user->id . '_' . $param['ids'], '240', 'pages/product/detail', $url);
            } else {
                $result = WeChatMini::getMiniScene($param['ids'], $param['ids'], '240', 'pages/product/detail', '/qrcode/product/product');
            }
        }
        return Result::success('获取成功！', $result);
    }
}
